<template>
  <div class="page-container">
    <div class="container">
  <el-container style="height: 100%;">
    <el-header>
      <h2>系统登录日志</h2>
    </el-header>
    <el-main>
      <el-table :data="logs" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="200"></el-table-column>
        <el-table-column prop="userId" label="用户ID" width="200"></el-table-column>
        <el-table-column prop="ipAddress" label="IP地址" ></el-table-column>
        <el-table-column prop="logTime" label="登录时间" >
          <template #default="scope">
            <span>{{ formatDate(scope.row.logTime) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          background
          layout="prev, pager, next"
          :total="pagination.total"
          :page-size="pagination.size"
          v-model:current-page="pagination.page"
          @current-change="fetchLogs"
          style="margin-top: 20px; text-align: center;"
      />
    </el-main>
  </el-container>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const logs = ref([]);
const loading = ref(false);
const pagination = ref({
  page: 1,
  size: 10,
  total: 0,
});

const fetchLogs = async () => {
  loading.value = true;
  try {
    const response = await axios.get('http://localhost:8080/admin/getSystemLog', {
      params: {
        page: pagination.value.page,
        size: pagination.value.size,
      },
    });
    if (response.data.code === 200) {
      logs.value = response.data.data.records;
      pagination.value.total = response.data.data.total;
    } else {
      ElMessage.error('获取登录日志失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
    console.error('Error fetching system logs:', error);
  } finally {
    loading.value = false;
  }
};
// 日期格式化
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(d.getDate()).padStart(2, '0'); // 日期补零
  const hours = String(d.getHours()).padStart(2, '0'); // 小时补零
  const minutes = String(d.getMinutes()).padStart(2, '0'); // 分钟补零
  const seconds = String(d.getSeconds()).padStart(2, '0'); // 秒补零

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

onMounted(() => {
  fetchLogs();
});
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>
